package map.geometry
{
	import flash.geom.Point;
	
	public class RadLine
	{
		public var p1:Point;
		public var p2:Point;
		public function RadLine(p1:Point,p2:Point)
		{
			super();
			this.p1 = p1;
			this.p2 = p2;
			pA_v = new Vector_2D(p1.x,p1.y);
			pB_v = new Vector_2D(p2.x,p2.y);
		}
		
		public var pA_v:Vector_2D = new Vector_2D();
		public var pB_v:Vector_2D = new Vector_2D();
		
		/**
		 * 
		 * @param ls
		 * @return 自身的两个点是否落在线段ls的两边
		 * 
		 */		
		private function intersectExtLine(ls:RadLine):Boolean{
			var temp_0_v:Vector_2D = new Vector_2D();
			var temp_1_v:Vector_2D = new Vector_2D();
			var temp_2_v:Vector_2D = new Vector_2D();
			
			//取得自身端点pA_v到端点pB_v的矢量,方向等同于自身的切向
			temp_0_v.x = pB_v.x - pA_v.x;
			temp_0_v.y = pB_v.y - pA_v.y;
			
			//取得目标线段的两个端点到自身端点pA_v对应的矢量
			temp_1_v.x = pA_v.x - ls.pA_v.x;
			temp_1_v.y = pA_v.y - ls.pA_v.y;
			//
			temp_2_v.x = pA_v.x - ls.pB_v.x;
			temp_2_v.y = pA_v.y - ls.pB_v.y;
			
			// 用矢量叉乘判断目标线段的两个端点是否在自己所在的直线的两侧                        
			return (temp_1_v.cross( temp_0_v ) * temp_2_v.cross( temp_0_v )) <= 0;
		}
		/**
		 用于检测ls线段是否和自己相交
		 */
		public function intersect(ls:RadLine):Boolean{
			//检测自己的延长线是否和ls线段相交                        
			if( intersectExtLine( ls ) ){
				//检测ls的延长线是否和自己的线段相交或重合                                
				return ls.intersectExtLine(this);
			}                        
			return false;
		}
		/**
		 * 
		 * @param ls
		 * @return 返回与线段ls的交点。如果不相交，返回null 
		 * 
		 */		
		public function intersectPoint(ls:RadLine):Point
		{
			var lsn:Vector_2D = ls.pA_v.minusNew(ls.pB_v);
			lsn.rotate(Math.PI/2);
			lsn.normalize();
			var ld1:Number = ls.pA_v.minusNew(this.pB_v).dot(lsn);
			var ld:Number = this.pA_v.minusNew(this.pB_v).dot(lsn);
			var k:Number = ld1/ld;
			var result:Point = null;
			if(k<=1.1&&k>=0)
			{
				result = Point.interpolate(p1,p2,k);
			}else
			{
				trace(k);
			}
			return result;
		}
		/**
		 * 
		 * @param p
		 * @return 点p到此线段的距离
		 * 
		 */		
		public function pointDistance(p:Point):Number
		{
			var n:Vector_2D = this.pA_v.minusNew(this.pB_v);
			n.rotate(Math.PI/2);
			n.normalize();
			return Math.abs(this.pA_v.minusNew(new Vector_2D(p.x,p.y)).dot(n));
		}
		
		public function get length():Number
		{
			return Point.distance(p1,p2);
		}
		
		public function equal(line:RadLine):Boolean
		{
			return this.pA_v.equals(line.pA_v) && this.pB_v.equals(line.pB_v);
		}
	}
}